<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\Store;

use App\Dao\StoreDao;
use App\Dao\StoreGroupDao;
use App\Kernel\Util\StoreJwtInstance;
use App\Service\Service;
use Hyperf\Di\Annotation\Inject;

/**
 * 用户登陆服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\Admin
 */
class StoreService extends Service
{
    /**
     * 后台用户
     *
     * @Inject
     * @var StoreDao
     */
    public $store_dao;

    /**
     * 后台角色Dao
     * @Inject()
     * @var StoreGroupDao
     */
    public $store_group_dao;


    /**
     * 权限服务
     * @Inject()
     * @var RightsService
     */
    public $rights_service;

    /**
     * 用户登录处理
     *
     * @param string $phone 手机号码
     * @param string $login_pwd  登录密码
     * @return array
     */
    public function login(string $phone, string $login_pwd)
    {

        // 获取或创建用户
        if (!$user = $this->store_dao->loginByPhone($phone)) {
            $this->error('USER.LOGIN_FAILED');
        }

        //验证密码
        if( !password_verify( $login_pwd, $user->login_pwd ) ) {
            $this->error('USER.REGISTER_FAIL');
        }

        // check user status
        if ($user->status !== true) {
            $this->error('USER.STATUS_EXCEPTION');
        }

        return [
            'token' => (string)StoreJwtInstance::instance()->encode($user),
        ];
    }

    /**
     * 添加后台用户的菜单数据
     * @param array $store
     * @return array
     */
    public function joinStoreMenus(array $store)
    {
        $group = $this->store_group_dao->getGroupById($store['group_id']);
        $store['group_name'] = $group['group_name'];

        if ($group['is_super'] == 1) {
            $store['is_super'] = true;
        } else {
            $store['is_super'] = false;
            if (!empty($group['auth_menus'])) {
                $auth_menus = $group['auth_menus'];
                $menus = $this->rights_service->getMenus($auth_menus, true);
                $store['menus'] = $menus;
            } else {
                $store['menus'] = [];
            }
        }

        return $store;
    }

}